package com.cqw.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-04-07 18:12
 * @Description: AES加密解密
 */
public class AESUtil {


    /**
     * 加密算法
     */
    private static final String ALGORITHM = "AES";

    /**
     * 默认编码
     */
    private static final String CHARSET = "utf-8";

    /**
     * 密钥
     */
    private static final String KEY = "key1234";

    /**
     * 密钥长度
     */
    private static final Integer KEY_LENGTH = 128;


    /**
     * AES加密
     *
     * @param content  需要被加密的字符串
     * @param password 加密需要的密码
     * @return
     */
    public static String encrypt(String content, String password) {
        try {
            SecretKeySpec key = generateKey(password);
            //创建密码器
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            byte[] byteContent = content.getBytes(CHARSET);
            //初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //加密
            byte[] result = cipher.doFinal(byteContent);
            //二进制转换成16进制字符串
            String hexStr = parseByte2HexStr(result);
            return hexStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 解密AES加密过的字符串
     *
     * @param content  AES加密过的内容
     * @param password 加密时的密码
     * @return
     */
    public static String decrypt(String content, String password) {

        try {
            //十六进制字符串转二进制字节数组
            byte[] byteArr = parseHexStr2Byte(content);
            SecretKeySpec key = generateKey(password);

            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            //解密
            byte[] result = cipher.doFinal(byteArr);
            return new String(result, CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 生成key
     *
     * @param password
     * @return
     */
    private static SecretKeySpec generateKey(String password) throws NoSuchAlgorithmException {
        //创建AES的key生产者
        KeyGenerator kGen = KeyGenerator.getInstance(ALGORITHM);
        //利用用户密码作为随机数初始化出
        //SecureRandom是生成安全随机数序列，password.getBytes()是种子，只要种子相同，序列就一样，所以解密只要有password就行
        kGen.init(KEY_LENGTH, new SecureRandom(password.getBytes()));
        //根据用户密码生成一个密钥
        SecretKey secretKey = kGen.generateKey();
        //返回基本编码格式的密钥，如果密钥不支持编码，则返回
        byte[] encodeFormat = secretKey.getEncoded();
        //转换为AES专用密钥
        SecretKeySpec key = new SecretKeySpec(encodeFormat, ALGORITHM);
        return key;
    }


    /**
     * 将二进制转为十六进制
     *
     * @param buf
     */
    private static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xff);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    /**
     * 十六进制转二进制
     *
     * @param hexStr
     * @return
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }


    public static void main(String[] args) {
        String encrypt = encrypt("曹青稳", "1234");
        System.out.println("加密：" + encrypt);

        String decrypt = decrypt(encrypt, "1234");
        System.out.println("解密：" + decrypt);
    }


}
